<!-- 新增和编辑弹窗 -->
<template>
  <a-modal
    :width='1100'
    :visible='visible'
    :confirm-loading='loading'
    :title="isUpdate ? '修改' : '新建'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible='updateVisible'
    @ok='save'
  >
    <a-form
      layout='horizontal'
      ref='form'
      :model='form'
      :rules='rules'
      :label-col='{ md: { span: 4 }, sm: { span: 24 } }'
      :wrapper-col='{ md: { span: 20 }, sm: { span: 24 } }'
    >
      <!--基本信息 -->
      <div class="card-title card-title-background">基本信息</div>
      <a-form-item label='告警策略名称:' name='objName'>
        <a-input v-model:value='form.objName' placeholder='请输入告警名称' allow-clear autocomplete='off'/>
      </a-form-item>

      <a-form-item label='告警级别:' name='alertLevel'>
        <a-select v-model:value="form.alertLevel">
          <a-select-option :value="1">严重</a-select-option>
          <a-select-option :value="2">警告</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label='触发规则条件:' name='alertSetRelate'>
        <a-select v-model:value="form.alertSetRelate">
          <a-select-option :value="1">满足任意一条规则触发</a-select-option>
          <a-select-option :value="2">满足全部规则触发</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label='告警描述:' name='objDesc'>
        <a-textarea v-model:value="form.objDesc" allow-clear autocomplete='off'/>
      </a-form-item>

      <a-form-item label='每天告警次数限制:' name='dateTimesLimit'>
        <a-select v-model:value="form.dateTimesLimit" style="width: 150px;"  @change="handleDateTimesLimit">
          <a-select-option :value="1">不限制</a-select-option>
          <a-select-option :value="2">限制</a-select-option>
        </a-select>
        <a-form-item-rest v-if="isShowDateTimesLimit">
          <a-input v-model:value='form.alertTimeLimit' placeholder='次数' allow-clear autocomplete='off'
                   style="width: 250px;"/>
        </a-form-item-rest>
      </a-form-item>

      <!--告警对象 -->
      <div class="card-title card-title-background">告警对象</div>
      <a-form-item label='所属业务:' name='ownerBiz'>
        <a-select v-model:value="form.ownerBiz" @change="handleOwnerBizChange">
          <a-select-option value="herd-hr-rr">牛群-呼吸心跳数据源</a-select-option>
          <a-select-option value="herd-rumen-temp">牛群-瘤胃温度数据源</a-select-option>
          <a-select-option value="device-sprayctocabinet">设备-喷淋控制柜数据源</a-select-option>
          <a-select-option value="device-envcontrol">设备-环控设备数据源</a-select-option>
          <a-select-option value="fence-hr-rr">牛栏-呼吸心跳数据源</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item v-if="ownerBizShow.isHerdShow" label="选择牛群:" name="ownerId">
        <a-select
          show-search
          v-model:value="form.ownerId"
          placeholder="请选择所属牛群"
          style="width: 205px;"
          :show-arrow="false"
          :filter-option="false"
          :not-found-content="null"
        >
          <a-select-option v-for="item in herdList" :key="item.herdId">
            {{ item.herdName }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
    <div>
      <MonitorsConfObjectsSubRule v-for="(item, index) in objectRules"
                                  :key="index" :index="index" :rule="item" @deleteIndex="removeRule"
                                  :ownerBizMonitorCodeNames="ownerBizMonitorCodeNames"
      />
    </div>

    <a-space>
      <a-button type="primary" @click="addRule">
        <template #icon>
          <plus-outlined/>
        </template>
        <span>新增策略规则</span>
      </a-button>
    </a-space>
  </a-modal>
</template>

<script>
import {MonitorObjectsApi} from '@/api/monitors/MonitorObjectsApi';
import {message} from 'ant-design-vue';
import {CattleHerdApi} from "@/api/property/cattlemanager/CattleHerdApi";
import {MonitorDimensionApi} from "@/api/monitors/MonitorDimensionApi";
import MonitorsConfObjectsSubRule from "./objects-sub-rule.vue";

export default {
  name: 'MonitorsConfObjectsEdit',
  components: {
    MonitorsConfObjectsSubRule
  },
  emits: ['done', 'update:visible'],
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object
  },
  created() {
    if (this.data) {
      let that = this;
      this.isUpdate = true;
      MonitorObjectsApi.detail({"objId": this.data.objId}).then(result => {
        if (result.rules && result.rules.length > 0) {
          let objectRulesArr = [];
          for (let i = 0; i < result.rules.length; i++) {
            let objectRuleItem = result.rules[i];
            if (objectRuleItem.tags != null && objectRuleItem.tags.length > 0) {
              objectRuleItem.tagsarr = objectRuleItem.tags.split(",");
            } else {
              objectRuleItem.tagsarr = [];
            }
            objectRulesArr.push(objectRuleItem);
          }
          this.objectRules = objectRulesArr;
        }
        this.form.objName = result.objName;
        this.form.objDesc = result.objDesc;
        this.form.ownerBiz = result.ownerBiz;
        this.form.ownerId = result.ownerId;
        this.form.objId = result.objId;
        this.form.alertLevel = result.alertLevel;
        this.form.alertSetRelate = result.alertSetRelate;
        //获取业务code
        if (result.ownerBiz == 'herd-hr-rr' || result.ownerBiz == 'herd-rumen-temp') {
          that.ownerBizShow.isHerdShow = true;
        }
        //-1不限制
        if (result.alertTimeLimit == -1) {
          that.isShowDateTimesLimit = false;
          that.form.dateTimesLimit = 1;
        } else {
          that.form.dateTimesLimit = 2;
          that.isShowDateTimesLimit = true;
          this.form.alertTimeLimit = result.alertTimeLimit;
        }
        MonitorDimensionApi.list({"ownerBiz": result.ownerBiz}).then(result => {
          let optionArr = [], length = result.length || 0;
          if (result && length > 0) {
            for (let i = 0; i < length; i++) {
              optionArr.push({
                value: result[i].monitorCode,
                label: result[i].monitorName,
              });
            }
          }
          that.ownerBizMonitorCodeNames = optionArr;
        }).catch((err) => {
          console.log(err)
        });
      });
    } else {
      this.form = {};
      this.form.dateTimesLimit = 1;
      this.isUpdate = false;
    }
    if (this.$refs.form) {
      this.$refs.form.clearValidate();
    }
  },
  data() {
    return {
      // 表单数据
      form: Object.assign({}, this.data),
      objectRules: [{"tagsarr": []}],
      // 表单验证规则
      rules: {
        objName: [{required: true, message: '请输入告警名称', type: 'string', trigger: 'blur'}],
        ownerBiz: [{required: true, message: '请选择所属业务', type: 'string', trigger: 'blur'}]
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      herdList: [],
      ownerBizShow: {
        isHerdShow: false
      },
      ownerBizMonitorCodeNames: [],
      isShowDateTimesLimit: false
    };
  },
  mounted() {
    CattleHerdApi.list({}).then(result => {
      this.herdList = (result ? result.data : null) || [];
    }).catch((err) => {
      console.log(err)
    });
  },
  methods: {
    /**
     * 保存和编辑
     *
     * @author cancan
     * @date 2023/05/27 21:37
     */
    async save() {
      console.log(this.form);
      // 校验表单
      await this.$refs.form.validate();

      // 修改加载框为正在加载
      this.loading = true;

      let result = null;

      // 执行编辑或修改
      if (this.isUpdate) {
        let updateObjectsFrom = {
          objName: this.form.objName,
          objDesc: this.form.objDesc,
          ownerBiz: this.form.ownerBiz,
          ownerId: this.form.ownerId,
          alertLevel: this.form.alertLevel,
          alertSetRelate: this.form.alertSetRelate,
          objId: this.form.objId,
          rules: this.objectRules,
        };
        if (this.form.dateTimesLimit == 1) {
          updateObjectsFrom.alertTimeLimit = -1;
        } else {
          updateObjectsFrom.alertTimeLimit = this.form.alertTimeLimit;
        }
        result = MonitorObjectsApi.edit(updateObjectsFrom);
      } else {
        let objectsFrom = {
          objName: this.form.objName,
          objDesc: this.form.objDesc,
          ownerBiz: this.form.ownerBiz,
          ownerId: this.form.ownerId,
          alertLevel: this.form.alertLevel,
          alertSetRelate: this.form.alertSetRelate,
          rules: this.objectRules
        };
        if (this.form.dateTimesLimit == 1) {
          objectsFrom.alertTimeLimit = -1;
        } else {
          objectsFrom.alertTimeLimit = this.form.alertTimeLimit;
        }
        result = MonitorObjectsApi.add(objectsFrom);
      }
      result
        .then(result => {
          // 移除加载框
          this.loading = false;

          // 提示添加成功
          message.success(result.message);

          // 如果是新增，则form表单置空
          if (!this.isUpdate) {
            this.form = {};
          }

          // 关闭弹框，通过控制visible的值，传递给父组件
          this.updateVisible(false);

          // 触发父组件done事件
          this.$emit('done');
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * 更新编辑界面的弹框是否显示
     *
     * @param value true-显示，false-隐藏
     * @author cancan
     * @date 2023/05/27 21:37
     */
    updateVisible(value) {
      this.$emit('update:visible', value);
    },
    handleOwnerBizChange(value) {
      let that = this;
      that.objectRules = [{"tagsarr": []}];
      if (value == 'herd-hr-rr' || value == 'herd-rumen-temp') {
        that.ownerBizShow.isHerdShow = true;
      } else {
        that.ownerBizShow.isHerdShow = false;
        that.form.ownerId = '';
      }
      MonitorDimensionApi.list({"ownerBiz": value}).then(result => {
        let optionArr = [], length = result.length || 0;
        if (result && length > 0) {
          for (let i = 0; i < length; i++) {
            optionArr.push({
              value: result[i].monitorCode,
              label: result[i].monitorName,
            });
          }
        }
        that.ownerBizMonitorCodeNames = optionArr;
      }).catch((err) => {
        console.log(err)
      });
    },
    handleDateTimesLimit(value) {
      let that = this;
      if (value == 1) { //无限制
        that.isShowDateTimesLimit = false;
        that.form.dateTimesLimit = 1;
      } else {
        that.isShowDateTimesLimit = true;
        this.form.alertTimeLimit = 0;
        that.form.dateTimesLimit = 2;
      }
    },
    addRule() {
      this.objectRules.push({"tagsarr": []});
    },
    removeRule(index) {
      if (index !== 0) {
        this.objectRules.splice(index, 1)
      }
    }
  }
};
</script>

<style lang="less" scoped>
.card-title {
  border-left: 5px solid;
  border-color: var(--primary-color);
  padding-left: 10px;
}

.card-title-background {
  background-color: #f5f5f5;
  height: 2em;
  line-height: 2em;
  margin-bottom: 2em;
}
</style>
